package com.tensai.study.java.newconcept.typereactiveprogram.reactor.flux.create.statics;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import reactor.core.publisher.Flux;

import java.util.ArrayList;
import java.util.Random;

/**
 * 该方法只能用来生成Flux，相对create而言，
 * generate在创建过程可以持久化一个state变量记录一些状态，类似闭包结构，
 * 通过一个回调函数进行对sink的操作，还可以对最后的state进行处理。
 * 当然generate可以像create一样使用
 *
 * @author Tensai
 */
@Slf4j
public class GenerateTest {


    /**
     * sink持续生成数据
     */
    @Test
    public void generateFlux() {
        Flux<Object> flux = Flux.
                generate(
                        () -> 0,
                        (i, sink) -> {
                            log.warn("i - {}", i);
                            sink.next(i * i);
                            if (i == 5) {
                                sink.complete();
                            }
                            return ++i;
                        },
                        state -> log.warn("the final state is:{}", state)
                ).log();

        flux.subscribe(System.out::println);
    }

    @Test
    public void csdn() {
        Flux.generate(sink -> {
            sink.next("Hello");
            sink.complete();
        }).subscribe(System.out::println);


        final Random random = new Random();
        Flux.generate(ArrayList::new, (list, sink) -> {
            int value = random.nextInt(100);
            list.add(value);
            sink.next(value);
            if (list.size() == 10) {
                sink.complete();
            }
            return list;
        }).subscribe(System.out::println);

    }


}
